import { useState, useMemo } from 'react';
import { useNavigate } from 'react-router-dom';
import { useLanguage } from '@kernelproxy/i18n';
import { useCart } from '../../contexts/CartContext';
import { ShoppingCart, Home, Globe, Package, Check } from 'lucide-react';
import * as flags from 'country-flag-icons/react/3x2';

type BillingPeriod = 'day' | 'week' | 'month' | 'year';

// 模拟国家库存数据
const countryInventory = [
  { code: 'US', name: 'United States', nameCN: '美国', stock: 1250 },
  { code: 'GB', name: 'United Kingdom', nameCN: '英国', stock: 850 },
  { code: 'DE', name: 'Germany', nameCN: '德国', stock: 920 },
  { code: 'FR', name: 'France', nameCN: '法国', stock: 780 },
  { code: 'JP', name: 'Japan', nameCN: '日本', stock: 650 },
  { code: 'CA', name: 'Canada', nameCN: '加拿大', stock: 540 },
  { code: 'AU', name: 'Australia', nameCN: '澳大利亚', stock: 480 },
  { code: 'SG', name: 'Singapore', nameCN: '新加坡', stock: 320 },
  { code: 'NL', name: 'Netherlands', nameCN: '荷兰', stock: 410 },
  { code: 'KR', name: 'South Korea', nameCN: '韩国', stock: 380 },
];

// 定价逻辑
const basePrices = {
  day: 0.03,
  week: 0.15,
  month: 0.45,
  year: 4.50,
};

// 批量折扣阶梯
const getDiscountRate = (quantity: number): number => {
  if (quantity >= 50) return 0.80;  // 20% off
  if (quantity >= 10) return 0.90;  // 10% off
  if (quantity >= 5) return 0.95;   // 5% off
  return 1.0;  // No discount
};

const PurchaseStaticResidential = () => {
  const { language } = useLanguage();
  const { addItem } = useCart();
  const navigate = useNavigate();
  
  // Create language-aware link helper
  const getLink = (path: string) => language === 'zh-CN' ? `/zh-CN${path}` : path;

  // Minimum quantities to meet Stripe's $0.50 minimum payment
  const minimumQuantities = {
    day: 17,    // $0.03 × 17 = $0.51
    week: 4,    // $0.15 × 4 = $0.60
    month: 2,   // $0.45 × 2 = $0.90
    year: 1,    // $4.50 × 1 = $4.50
  };

  // State management
  const [billingPeriod, setBillingPeriod] = useState<BillingPeriod>('month');
  const [quantity, setQuantity] = useState<number>(minimumQuantities.month);
  const [selectedCountry, setSelectedCountry] = useState<string>('US');

  const selectedCountryData = useMemo(
    () => countryInventory.find(c => c.code === selectedCountry) || countryInventory[0],
    [selectedCountry]
  );

  // Period labels
  const periodLabels = {
    day: language === 'zh-CN' ? '天' : 'Day',
    week: language === 'zh-CN' ? '周' : 'Week',
    month: language === 'zh-CN' ? '月' : 'Month',
    year: language === 'zh-CN' ? '年' : 'Year',
  };

  // 计算总价
  const totalPrice = useMemo(() => {
    const basePrice = basePrices[billingPeriod];
    const discountRate = getDiscountRate(quantity);
    return (basePrice * quantity * discountRate).toFixed(2);
  }, [billingPeriod, quantity]);

  // 计算单价
  const unitPrice = useMemo(() => {
    const basePrice = basePrices[billingPeriod];
    const discountRate = getDiscountRate(quantity);
    return (basePrice * discountRate).toFixed(3);
  }, [billingPeriod, quantity]);

  // Calculate discount percentage
  const discountPercentage = useMemo(() => {
    const rate = getDiscountRate(quantity);
    return rate === 1.0 ? 0 : Math.round((1 - rate) * 100);
  }, [quantity]);

  // Add to cart handler
  const handleAddToCart = () => {
    const discountValue = discountPercentage / 100;
    addItem({
      productType: 'static-residential',
      quantity,
      period: billingPeriod,
      country: selectedCountry,
      countryName: language === 'zh-CN' ? selectedCountryData.nameCN : selectedCountryData.name,
      unitPrice: parseFloat(unitPrice),
      totalPrice: parseFloat(totalPrice),
      ...(discountValue > 0 && { discount: discountValue }),
    });
    navigate(getLink('/dashboard/cart'));
  };

  return (
    <div className="min-h-screen bg-gradient-to-br from-blue-50 via-white to-purple-50 dark:from-gray-900 dark:via-gray-800 dark:to-gray-900 py-12 px-4 sm:px-6 lg:px-8">
      <div className="max-w-7xl mx-auto">
        {/* Header */}
        <div className="text-center mb-12">
          <div className="inline-flex items-center justify-center p-3 bg-blue-100 dark:bg-blue-900/30 rounded-full mb-4">
            <Home className="text-blue-600 dark:text-blue-400" size={32} />
          </div>
          <h1 className="text-4xl font-bold text-gray-900 dark:text-white mb-4">
            {language === 'zh-CN' ? '静态住宅 IPv6 选购' : 'Static Residential IPv6 Purchase'}
          </h1>
          <p className="text-lg text-gray-600 dark:text-gray-300">
            {language === 'zh-CN' 
              ? '自定义您的静态住宅 IPv6 代理套餐，选择数量、周期和国家' 
              : 'Customize your Static Residential IPv6 proxy plan - choose quantity, period, and country'}
          </p>
        </div>

        <div className="grid lg:grid-cols-3 gap-8">
          {/* Configuration Panel */}
          <div className="lg:col-span-2 space-y-6">
            {/* Billing Period Selection */}
            <div className="bg-white dark:bg-gray-800 rounded-lg shadow-lg p-6">
              <div className="flex items-center mb-4">
                <Package className="w-5 h-5 text-blue-600 dark:text-blue-400 mr-2" />
                <h2 className="text-xl font-semibold text-gray-900 dark:text-white">
                  {language === 'zh-CN' ? '选择计费周期' : 'Select Billing Period'}
                </h2>
              </div>
              <div className="grid grid-cols-2 md:grid-cols-4 gap-3">
                {(Object.keys(periodLabels) as BillingPeriod[]).map((period) => (
                  <button
                    key={period}
                    onClick={() => {
                      setBillingPeriod(period);
                      // Reset quantity to minimum when changing billing period
                      setQuantity(minimumQuantities[period]);
                    }}
                    className={`p-4 rounded-lg border-2 transition-all ${
                      billingPeriod === period
                        ? 'border-blue-600 bg-blue-50 dark:bg-blue-900/30 dark:border-blue-400 text-gray-900 dark:text-white'
                        : 'border-gray-200 dark:border-gray-700 hover:border-blue-400 dark:hover:border-blue-500 text-gray-700 dark:text-gray-200'
                    }`}
                  >
                    <div className="text-center">
                      <div className="text-lg font-medium mb-1">
                        {periodLabels[period]}
                      </div>
                      <div className="text-sm text-gray-600 dark:text-gray-400">
                        ${basePrices[period].toFixed(2)}/{language === 'zh-CN' ? 'IP' : 'IP'}
                      </div>
                    </div>
                  </button>
                ))}
              </div>
            </div>

            {/* Quantity Selection */}
            <div className="bg-white dark:bg-gray-800 rounded-lg shadow-lg p-6">
              <div className="flex items-center justify-between mb-4">
                <div className="flex items-center">
                  <Home className="w-5 h-5 text-blue-600 dark:text-blue-400 mr-2" />
                  <h2 className="text-xl font-semibold text-gray-900 dark:text-white">
                    {language === 'zh-CN' ? '选择 IP 数量' : 'Select IP Quantity'}
                  </h2>
                </div>
                {discountPercentage > 0 && (
                  <span className="bg-green-500 text-white text-xs font-bold px-3 py-1 rounded-full">
                    {language === 'zh-CN' ? `立省 ${discountPercentage}%` : `${discountPercentage}% OFF`}
                  </span>
                )}
              </div>
              
              <div className="space-y-4">
                <div className="flex items-center gap-4">
                  <input
                    type="range"
                    min={minimumQuantities[billingPeriod]}
                    max="100"
                    value={quantity}
                    onChange={(e) => setQuantity(parseInt(e.target.value))}
                    className="flex-1 h-2 bg-gray-200 dark:bg-gray-700 rounded-lg appearance-none cursor-pointer accent-blue-600"
                  />
                  <input
                    type="number"
                    min={minimumQuantities[billingPeriod]}
                    max={selectedCountryData.stock}
                    value={quantity}
                    onChange={(e) => setQuantity(Math.max(minimumQuantities[billingPeriod], Math.min(selectedCountryData.stock, parseInt(e.target.value) || minimumQuantities[billingPeriod])))}
                    className="w-20 px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-lg text-center font-bold text-gray-900 dark:text-white bg-white dark:bg-gray-700"
                  />
                </div>
                
                {/* Quick Select Buttons */}
                <div className="flex flex-wrap gap-2">
                  {[20, 50, 100, 200].map((num) => (
                    <button
                      key={num}
                      onClick={() => setQuantity(Math.min(num, selectedCountryData.stock))}
                      className={`px-4 py-2 rounded-lg border transition-all duration-300 ${
                        quantity === num
                          ? 'border-blue-600 bg-blue-50 dark:bg-blue-900/30 text-gray-900 dark:text-white font-bold'
                          : 'border-gray-300 dark:border-gray-600 hover:border-blue-400 dark:hover:border-blue-500 text-gray-700 dark:text-gray-200'
                      }`}
                    >
                      {num} {language === 'zh-CN' ? '个' : 'IPs'}
                    </button>
                  ))}
                </div>

                {/* Discount Tiers Info */}
                <div className="bg-blue-50 dark:bg-blue-900/20 border border-blue-200 dark:border-blue-800 rounded-lg p-4">
                  <p className="text-sm font-semibold text-blue-900 dark:text-blue-200 mb-2">
                    {language === 'zh-CN' ? '批量优惠' : 'Volume Discounts'}:
                  </p>
                  <ul className="text-xs text-blue-800 dark:text-blue-300 space-y-1">
                    <li className="flex items-center">
                      <Check size={14} className="mr-2" />
                      {language === 'zh-CN' ? '5-9 个 IP: 5% 折扣' : '5-9 IPs: 5% off'}
                    </li>
                    <li className="flex items-center">
                      <Check size={14} className="mr-2" />
                      {language === 'zh-CN' ? '10-49 个 IP: 10% 折扣' : '10-49 IPs: 10% off'}
                    </li>
                    <li className="flex items-center">
                      <Check size={14} className="mr-2" />
                      {language === 'zh-CN' ? '50+ 个 IP: 20% 折扣' : '50+ IPs: 20% off'}
                    </li>
                  </ul>
                </div>
              </div>
            </div>

            {/* Country Selection */}
            <div className="bg-white dark:bg-gray-800 rounded-lg shadow-lg p-6">
              <div className="flex items-center mb-4">
                <Globe className="w-5 h-5 text-blue-600 dark:text-blue-400 mr-2" />
                <h2 className="text-xl font-semibold text-gray-900 dark:text-white">
                  {language === 'zh-CN' ? '选择国家/地区' : 'Select Country/Region'}
                </h2>
              </div>
              
              <div className="grid grid-cols-2 md:grid-cols-3 lg:grid-cols-5 gap-3">
                {countryInventory.map((country) => {
                  const FlagComponent = flags[country.code as keyof typeof flags];
                  return (
                    <button
                      key={country.code}
                      onClick={() => {
                        setSelectedCountry(country.code);
                        if (quantity > country.stock) {
                          setQuantity(country.stock);
                        }
                      }}
                      disabled={country.stock === 0}
                      className={`p-3 rounded-lg border-2 transition-all duration-300 ${
                        selectedCountry === country.code
                          ? 'border-blue-600 bg-blue-50 dark:bg-blue-900/30'
                          : 'border-gray-200 dark:border-gray-700 hover:border-blue-400 dark:hover:border-blue-500'
                      } ${country.stock === 0 ? 'opacity-50 cursor-not-allowed' : ''}`}
                    >
                      <div className="w-full h-8 mb-2 flex items-center justify-center">
                        {FlagComponent && <FlagComponent className="w-10 h-7 rounded shadow-sm" />}
                      </div>
                      <div className="text-xs font-semibold text-gray-900 dark:text-white">
                        {language === 'zh-CN' ? country.nameCN : country.name}
                      </div>
                      <div className={`text-xs mt-1 ${
                        country.stock > 100 
                          ? 'text-green-600 dark:text-green-400' 
                          : country.stock > 20
                          ? 'text-yellow-600 dark:text-yellow-400'
                          : 'text-red-600 dark:text-red-400'
                      }`}>
                        {language === 'zh-CN' ? '库存' : 'Stock'}: {country.stock}
                      </div>
                    </button>
                  );
                })}
              </div>
            </div>

            {/* Features Info */}
            <div className="bg-white dark:bg-gray-800 rounded-lg shadow-lg p-6">
              <h3 className="text-lg font-semibold text-gray-900 dark:text-white mb-4">
                {language === 'zh-CN' ? '套餐包含' : 'Package Includes'}
              </h3>
              <div className="grid md:grid-cols-2 gap-4 text-sm text-gray-700 dark:text-gray-300">
                <div className="flex items-start">
                  <div className="w-2 h-2 bg-blue-600 rounded-full mt-1.5 mr-2 flex-shrink-0"></div>
                  <span>{language === 'zh-CN' ? '真实住宅 IP，高匿名性' : 'Real residential IPs with high anonymity'}</span>
                </div>
                <div className="flex items-start">
                  <div className="w-2 h-2 bg-blue-600 rounded-full mt-1.5 mr-2 flex-shrink-0"></div>
                  <span>{language === 'zh-CN' ? '专属 IP，独享资源' : 'Dedicated IPs, exclusive resources'}</span>
                </div>
                <div className="flex items-start">
                  <div className="w-2 h-2 bg-blue-600 rounded-full mt-1.5 mr-2 flex-shrink-0"></div>
                  <span>{language === 'zh-CN' ? 'HTTP/HTTPS/SOCKS5 协议' : 'HTTP/HTTPS/SOCKS5 protocols'}</span>
                </div>
                <div className="flex items-start">
                  <div className="w-2 h-2 bg-blue-600 rounded-full mt-1.5 mr-2 flex-shrink-0"></div>
                  <span>{language === 'zh-CN' ? '无限带宽和并发' : 'Unlimited bandwidth and concurrency'}</span>
                </div>
                <div className="flex items-start">
                  <div className="w-2 h-2 bg-blue-600 rounded-full mt-1.5 mr-2 flex-shrink-0"></div>
                  <span>{language === 'zh-CN' ? '99.9% 正常运行时间' : '99.9% uptime guarantee'}</span>
                </div>
                <div className="flex items-start">
                  <div className="w-2 h-2 bg-blue-600 rounded-full mt-1.5 mr-2 flex-shrink-0"></div>
                  <span>{language === 'zh-CN' ? '24/7 技术支持' : '24/7 technical support'}</span>
                </div>
              </div>
            </div>
          </div>

          {/* Order Summary - Sticky Sidebar */}
          <div className="lg:col-span-1">
            <div className="bg-white dark:bg-gray-800 rounded-lg shadow-lg p-6 sticky top-20 border-2 border-gray-200 dark:border-[#00d4ff]/30">
              <div className="flex items-center mb-6">
                <ShoppingCart className="w-5 h-5 text-blue-600 dark:text-blue-400 mr-2" />
                <h2 className="text-xl font-semibold text-gray-900 dark:text-white">
                  {language === 'zh-CN' ? '订单摘要' : 'Order Summary'}
                </h2>
              </div>

              <div className="space-y-4 mb-6">
                {/* Product */}
                <div className="flex justify-between text-sm pb-3 border-b border-gray-200 dark:border-gray-700">
                  <span className="text-gray-600 dark:text-gray-400">
                    {language === 'zh-CN' ? '产品' : 'Product'}:
                  </span>
                  <span className="font-medium text-gray-900 dark:text-white">
                    {language === 'zh-CN' ? '静态住宅 IPv6' : 'Static Residential IPv6'}
                  </span>
                </div>

                {/* Quantity */}
                <div className="flex justify-between text-sm pb-3 border-b border-gray-200 dark:border-gray-700">
                  <span className="text-gray-600 dark:text-gray-400">
                    {language === 'zh-CN' ? '数量' : 'Quantity'}:
                  </span>
                  <span className="font-medium text-gray-900 dark:text-white">
                    {quantity} {quantity === 1 ? 'IP' : 'IPs'}
                  </span>
                </div>

                {/* Billing Period */}
                <div className="flex justify-between text-sm pb-3 border-b border-gray-200 dark:border-gray-700">
                  <span className="text-gray-600 dark:text-gray-400">
                    {language === 'zh-CN' ? '计费周期' : 'Billing Period'}:
                  </span>
                  <span className="font-medium text-gray-900 dark:text-white">
                    {periodLabels[billingPeriod]}
                  </span>
                </div>

                {/* Country */}
                <div className="flex justify-between text-sm pb-3 border-b border-gray-200 dark:border-gray-700">
                  <span className="text-gray-600 dark:text-gray-400">
                    {language === 'zh-CN' ? '国家' : 'Country'}:
                  </span>
                  <span className="font-medium text-gray-900 dark:text-white flex items-center gap-2">
                    {(() => {
                      const FlagComponent = flags[selectedCountryData.code as keyof typeof flags];
                      return FlagComponent && <FlagComponent className="w-5 h-3.5 rounded shadow-sm inline-block" />;
                    })()}
                    {language === 'zh-CN' ? selectedCountryData.nameCN : selectedCountryData.name}
                  </span>
                </div>

                {/* Unit Price */}
                <div className="flex justify-between text-sm pb-3 border-b border-gray-200 dark:border-gray-700">
                  <span className="text-gray-600 dark:text-gray-400">
                    {language === 'zh-CN' ? '单价' : 'Unit Price'}:
                  </span>
                  <span className="font-medium text-gray-900 dark:text-white">
                    ${unitPrice}/{language === 'zh-CN' ? 'IP' : 'IP'}
                  </span>
                </div>

                {/* Discount */}
                {discountPercentage > 0 && (
                  <div className="flex justify-between text-sm pb-3 border-b border-gray-200 dark:border-gray-700">
                    <span className="text-gray-600 dark:text-gray-400">
                      {language === 'zh-CN' ? '折扣' : 'Discount'}:
                    </span>
                    <span className="font-medium text-green-600 dark:text-green-400">
                      -{discountPercentage}%
                    </span>
                  </div>
                )}

                <div className="pt-4">
                  <div className="flex justify-between items-center">
                    <span className="text-lg font-semibold text-gray-900 dark:text-white">
                      {language === 'zh-CN' ? '总计' : 'Total'}:
                    </span>
                    <span className="text-2xl font-bold text-blue-600 dark:text-blue-400">
                      ${totalPrice}
                    </span>
                  </div>
                  <div className="text-xs text-gray-500 dark:text-gray-400 text-right mt-1">
                    {language === 'zh-CN' 
                      ? `按${periodLabels[billingPeriod]}计费` 
                      : `per ${periodLabels[billingPeriod]}`}
                  </div>
                </div>
              </div>

              {/* Action Buttons */}
              <div className="space-y-3">
                <button
                  className="w-full bg-gradient-to-r from-blue-600 to-indigo-600 hover:from-blue-700 hover:to-indigo-700 text-white font-medium py-3 px-6 rounded-lg transition-all duration-200"
                  onClick={handleAddToCart}
                >
                  <span className="flex items-center justify-center gap-2">
                    <ShoppingCart size={20} />
                    {language === 'zh-CN' ? '加入购物车' : 'Add to Cart'}
                  </span>
                </button>

                <button
                  className="w-full border border-gray-300 dark:border-gray-600 hover:bg-gray-50 dark:hover:bg-gray-700 text-gray-700 dark:text-gray-200 font-medium py-3 px-6 rounded-lg transition-all duration-200"
                  onClick={() => navigate(getLink('/dashboard'))}
                >
                  {language === 'zh-CN' ? '返回仪表板' : 'Back to Dashboard'}
                </button>
              </div>

              {/* Additional Info */}
              <div className="mt-6 text-xs text-gray-500 dark:text-gray-400 space-y-2">
                <p>
                  {language === 'zh-CN' 
                    ? '• 购买后立即激活'
                    : '• Instant activation after purchase'}
                </p>
                <p>
                  {language === 'zh-CN' 
                    ? '• 支持多种支付方式'
                    : '• Multiple payment methods supported'}
                </p>
                <p>
                  {language === 'zh-CN' 
                    ? '• 专属 IP，独享资源'
                    : '• Dedicated IPs, exclusive resources'}
                </p>
                <p>
                  {language === 'zh-CN' 
                    ? '• 7 天退款保证'
                    : '• 7-day money-back guarantee'}
                </p>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
};

export default PurchaseStaticResidential;
